package com.martinzhuang.how_old;

import android.graphics.Bitmap;

import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;

/**
 * Created by martinzhuang on 9/22/15.
 */
public class FaceppDetect {

    interface CallBack {
        void success(JSONObject result);

        void error(FaceppParseException exception);
    }

    public static void detect(final Bitmap bitmap, final CallBack callBack) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //make a request and then compress photo to binary
                    HttpRequests httpRequests = new HttpRequests(Constant.KEY, Constant.SECRET, true, false);
                    Bitmap bitmapSmall = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmapSmall.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

                    //binary data of photo
                    byte[] arrays = byteArrayOutputStream.toByteArray();

                    //set img to params
                    PostParameters postParameters = new PostParameters();
                    postParameters.setImg(arrays);

                    //request for result
                    JSONObject jsonObject = httpRequests.detectionDetect(postParameters);

                    System.out.println(jsonObject.toString());

                    //then call back
                    if (callBack != null) {
                        callBack.success(jsonObject);
                    }

                } catch (FaceppParseException e) {
                    e.printStackTrace();

                    if (callBack != null) {
                        callBack.error(e);
                    }
                }
            }
        }).start();

    }

}
